<template>
  <xdh-layout fixed :west="{width:'300px', split:true}">
    <xdh-panel slot="west"
               :fit="true"
               title="组织结构">
      <template slot="tool">
        <el-input size="mini" :clearable="true" placeholder="输入关键字进行过滤"
                  v-model="filterText">
        </el-input>
      </template>
      <el-tree
        :data="orgList"
        node-key="id"
        :highlight-current="true"
        :props="defaultProps"
        :check-strictly="true"
        :expand-on-click-node="false"
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
        v-loading="treeLoading"
        class="orgTree xdh-tree"
        ref="orgRef">
      </el-tree>
    </xdh-panel>

    <xdh-curd ref="curd"
              :filter="false"
              :collapsible="false"
              name="sysUser"
              :model="model"
              :rules="rules"
              :mixin="mixin"
              :query="listQuery"
              :is-auto="false"
              dialogWidth="600px"
              model-key="pkValue"
              :handleType="'icon'"
              :removeDisabled="removeDisabled"
              @on-error="errorList"
              @on-success="successList"
              :listTitle="`${model.parentName} 属下用户`">

      <!-- 数据列表 -->
      <template slot="table-columns"
                slot-scope="scope">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="xm" label="名称" min-width="100"></el-table-column>
        <el-table-column prop="jh" label="警号" min-width="100"></el-table-column>
        <el-table-column prop="ssjg" label="所属机构" min-width="100"></el-table-column>
        <el-table-column prop="jsmc" label="角色" min-width="100"></el-table-column>
        <el-table-column prop="yxq" label="有效期" min-width="100"></el-table-column>
        <!--<el-table-column prop="isDefault" label="是否总队业务支队" min-width="60">-->
          <!--<template slot-scope="scope">-->
            <!--<el-tag size="mini" v-if="scope.row.zdywzd === '1'">是</el-tag>-->
            <!--<el-tag size="mini" type="danger" v-else>否</el-tag>-->
          <!--</template>-->
        <!--</el-table-column>-->
      </template>
      <template slot="table-handle-column" slot-scope="prop">
        <el-tooltip content="角色选择" placement="top">
          <el-button size="mini" @click="handleViewFlow(prop.row)">
            <i class="iconfont icon-app" style="line-height:0.5;"></i>
          </el-button>
        </el-tooltip>
      </template>
      <!-- 数据新增编辑弹窗 -->
      <template slot="dialog-form-items"
                slot-scope="prop">
        <!--<el-form-item label="所属机构" prop="parentId">-->
        <!--{{model.parentName}}-->
        <!--</el-form-item>-->
        <el-form-item label="姓名" prop="xm" class="row-cls-2">
          <el-input v-model="prop.model.xm"></el-input>
        </el-form-item>
        <el-form-item label="证件" prop="zjhm" class="row-cls-2">
          <el-input v-model="prop.model.zjhm"></el-input>
        </el-form-item>
        <el-form-item label="警号" prop="username" class="row-cls-2">
          <el-input v-model="prop.model.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="row-cls-2">
          <el-input v-model="prop.model.password"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="lxdh" class="row-cls-2">
          <el-input v-model="prop.model.lxdh"></el-input>
        </el-form-item>
        <el-form-item label="所属机构" prop="dw" class="row-cls-2">
          <select-tree-org
            @on-selected-keys="onSelectFormOrg"
            :showSelectNum="false"
            :value="[prop.model.dw]"
            placeholder="组织"
          >
          </select-tree-org>
          <!--<el-input v-model="prop.model.ssjg"></el-input>-->
        </el-form-item>
        <el-form-item label="岗位" prop="gw" class="row-cls-2">
          <el-input v-model="prop.model.gw"></el-input>
        </el-form-item>
        <el-form-item label="职级" prop="zj" class="row-cls-2">
          <el-input v-model="prop.model.zj"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="yxq" class="row-cls-2">
          <el-date-picker
            v-model="prop.model.yxq"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="bz">
          <el-input type="textarea" :rows="2" v-model="prop.model.bz"></el-input>
        </el-form-item>
      </template>
    </xdh-curd>

    <xdh-dialog title="角色选择"
                :closed.sync="flowDialogVisible"
                width="80%"
                @on-open="openRoleList"
                height="50%">
      <el-table
        ref="multipleTable"
        :data="roleList"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="jsmc"
          label="角色">
        </el-table-column>
        <el-table-column
          prop="createdtime"
          label="创建时间">
        </el-table-column>
        <el-table-column
          prop="deleteflag"
          label="是否启用">
          <template slot-scope="scope">
            <el-tag size="mini" type="danger" v-if="scope.row.zdywzd === '1'">警用</el-tag>
            <el-tag size="mini" v-else>启用</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button @click="submitRole">确定</el-button>
      </div>
    </xdh-dialog>
  </xdh-layout>
</template>
<style type="text/scss" lang="scss" scoped>
  .orgTree {
    display: table;
    width: 100%;
  }

  .row-cls-2 {
    display: inline-block;
    width: 49%;
  }

  .xdh-layout__west /deep/ .xdh-layout--split {
    margin: 10px;
  }
</style>

<script>
  import XdhLayout from '../../widgets/xdh-layout'
  import XdhCurd from '../../widgets/xdh-curd'
  import xdhPanel from '../../widgets/xdh-panel'
  import XdhDialog from '../../widgets/xdh-dialog'
  import sysUser from '../../base/mixin/sys-user'
  import {clone} from '../../utils/convert'
  import {getOrgTree, updateOrgTreeStore} from '../../helper/before'
  import sysDictionary from '../../base/mixin/sys-dictionary'
  import SelectTreeOrg from '../../components/select-tree-org'
  import {mapState} from 'vuex'

  export default {
    components: {
      XdhCurd,
      xdhPanel,
      XdhDialog,
      SelectTreeOrg,
      XdhLayout
    },
    mixins: [sysUser, sysDictionary],
    computed: {
      ...mapState({
        orgTree: state => state.sysOrgTree.orgTree || null
      })
    },
    data() {
      return {
        mixin: sysUser,
        defaultExpandedKeys: [],
        orgList: [],
        roleList: [],
        rolepkValue: '',
        SelectionRoleList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        selectNode: {},
        model: {
          lxdh: '', // 联系电话
          ssjg: '', // 所属机构
          gw: '', // 岗位
          zj: '', // 职级
          dw: '', // 单位
          yxq: '', // 有效期
          xm: '', // 姓名
          zjhm: '', // 证件号码
          bz: '', // 备注
          username: '', // 警号
          password: ''  // 密码
        },
        listQuery: {},
        hasAddReload: false, // 添加节点操作后的列表加载
        flowDialogVisible: true,
        rules: {
          xm: [{
            required: true,
            message: '必需填写姓名'
          }],
          username: [{
            required: true,
            message: '必需填写警号'
          }]
        },
        filterText: '',
        treeLoading: false
      }
    },
    methods: {
      /**
       * 组织筛选
       */
      filterNode(value, data) {
        if (!value) return true
        return data[this.defaultProps.label].indexOf(value) !== -1
      },
      /**
       * 点击左侧菜单树选择
       * @param data
       * @param node
       * @param r
       */
      nodeClick(data, node, r) {
        this.selectNode = data
        this.listQuery = {}
        this.listQuery.keyword = data.pid
        this.model.parentId = data.pid
        this.model.parentName = data.label
        this.$nextTick(() => {
          this.$refs.curd.reload()
        })
      },
      /**
       * 默认选中和展开第一个树节点
       */
      defaultSetCurrentTree(noLoadKey = false) {
        this.$nextTick(() => {
          let currentKey = this.orgList[0]
          if (!noLoadKey) {
            currentKey = this.selectNode
          }
          this.$refs['orgRef'].setCurrentKey(currentKey.id)
          this.defaultExpandedKeys = [currentKey.id]
          this.nodeClick(currentKey)
          this.loading = false
        })
      },
      /**
       * 查询组织树
       */
      queryTree(isLoadCurrentKey = true) {
        if (!this.orgTree) {
          this.treeLoading = true
          getOrgTree().then(d => {
            this.orgList = clone(d)
            if (this.orgList.length > 0) {
              this.defaultSetCurrentTree(isLoadCurrentKey)
            }
            this.treeLoading = false
          })
        } else {
          this.orgList = clone(this.orgTree)
          if (this.orgList.length > 0) {
            this.defaultSetCurrentTree(isLoadCurrentKey)
          }
        }
      },
      errorList(type, data) {
        this.$message({
          type: 'error',
          message: data.msg
        })
      },
      /**
       * 角色选择
       * @param row
       */
      handleViewFlow(row) {
        if (row.js.length) {
          let arr = [];
          row.js.forEach(list => {
            arr.push(this.roleList.find(val => val.id === list))
          });
          this.SelectionRoleList = arr
        }
        this.rolepkValue = row.pkValue
        this.flowDialogVisible = !this.flowDialogVisible
      },
      openRoleList() {
        this.$nextTick(function () {
          this.SelectionRoleList.forEach(val => {
            this.$refs.multipleTable.toggleRowSelection(val);
          })
        })
      },
      closeDialog() {
        this.flowDialogVisible = !this.flowDialogVisible
      },
      submitRole() {
        let jsArr = [];
        this.SelectionRoleList.forEach(val => {
          jsArr.push(val.id)
        })
        this.patchUserControl({pkValue: this.rolepkValue, js: jsArr}).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.closeDialog()
        }).catch(err => {
          this.$message({
            message: err + '保存失败!',
            type: 'error'
          })
        })
      },
      handleSelectionChange(row) {
        this.SelectionRoleList = row
      },
      /**
       * 列表数据请求成功回调
       */
      successList(type, data) {
        if (this.hasAddReload && type === 'fetch') {
          // todo: 添加操作后的列表查询 添加成功接口未返回新数据主键的退选处理,新增接口调整后 再处理优化
          if (this.selectNode.list.length > 0) {
            // this.$refs.orgRef.insertBefore
          } else {
            this.$refs.orgRef.updateKeyChildren(this.selectNode.pkValue, data.list)
          }
          this.hasAddReload = false
          // 更新OrgTreeStore 状态
          updateOrgTreeStore(this.orgList[0])
        }

        if (type === 'add') {
          this.$refs.curd.reload()
          this.hasAddReload = true // 是否是添加后的加载
        }

        if (type === 'remove') {
          this.$refs.orgRef.remove(data.pkValue)
          // 更新OrgTreeStore 状态
          updateOrgTreeStore(this.orgList[0])
        }

        if (type === 'update') {
          let childrenList = this.selectNode.list || []
          this.$refs.orgRef.updateKeyChildren(this.selectNode.pkValue, childrenList.map(item => {
            if (item.pkValue === data.pkValue) {
              return data
            }
            return item
          }))
          // 更新OrgTreeStore 状态
          updateOrgTreeStore(this.orgList[0])
        }
      },
      removeDisabled(row) {
        return row.isDefault
      },
      onSelectFormOrg(keys) {
        this.model.dw = keys[0] || '';
        // this.model.orgName = '';
      }
    },
    watch: {
      filterText(val) {
        this.$refs.orgRef.filter(val)
      }
    },
    mounted() {
      // 角色列表
      this.getUserControl().then(res => {
        this.roleList = res
      })
    },
    created() {
      this.queryTree()
    }
  }
</script>

